package org.springblade.modules.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ijpay.core.enums.SignType;
import com.ijpay.core.kit.WxPayKit;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.model.OrderQueryModel;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.config.WxPayConfig;
import org.springblade.common.constant.OrderConstant;
import org.springblade.common.utils.DecimalUtil;
import org.springblade.common.utils.JpushTemplate;
import org.springblade.modules.app.entity.*;
import org.springblade.modules.app.service.*;
import org.springblade.modules.netty.NettyHandler;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Configuration
@EnableScheduling
public class FrameTask {

    @Autowired
    private ICoalService coalService;

    @Autowired
    private IMoneyDetailService moneyDetailService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IOrderPoundageService orderPoundageService;

    @Autowired
    private IJpushService jpushService;

    @Autowired
    private ICouponsService couponsService;

    @Scheduled(cron = "0/10 * * * * ?")
    public void configureTasks() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<Order>();
        queryWrapper.and(wrapper -> wrapper.eq(Order::getOrderstatus, 3));
        ///后续是否查询只查询一段的//问题
        //queryWrapper.between(SysUser::getCreateTime,params.getStartTime(),params.getEndTime());
//        queryWrapper.apply("date_format(ctime,'%Y-%m-%d')={0}", sdf.format(new Date()));
        List<Order> list = coalService.list(queryWrapper);
        for (Order entity : list) {
            Map<String, String> params = OrderQueryModel.builder()
                    .nonce_str(IdWorker.getIdStr())
                    .mch_id(WxPayConfig.mchId)
                    .appid(WxPayConfig.appId)
                    .out_trade_no(entity.getId() + "")
                    .build()
                    .createSign(WxPayConfig.partnerKey, SignType.MD5, false);
            String orderQuery = WxPayApi.orderQuery(params);
            Map<String, String> result = WxPayKit.xmlToMap(orderQuery);
            //  log.info("===" + result);


            String returnCode = result.get("return_code");
            String resultCode = result.get("result_code");
            String transaction_id = result.get("transaction_id");
            String trade_state = result.get("trade_state");

            if (WxPayKit.codeIsOk(returnCode) && WxPayKit.codeIsOk(resultCode)) {

                if (WxPayKit.codeIsOk(trade_state)) {
                    Order orderInfo = coalService.getById(entity.getId());

                    if (OrderConstant.ORDER_STATUS_4.equals(orderInfo.getOrderstatus()) && "1".equals(orderInfo.getQxstatus())) {
                        //   log.info("正常 不在处理");
                        continue;
                    }

                    if ("3".equals(orderInfo.getQxstatus())) {
                        //      log.info("正常 不在处理");
                        continue;
                    }

                    User workerUserInfo = userService.getById(orderInfo.getWorkerid());

                    if (OrderConstant.ORDER_STATUS_3.equals(orderInfo.getOrderstatus()) && "1".equals(orderInfo.getQxstatus())) {

                        orderInfo.setTradeno(transaction_id);
                        orderInfo.setOrderstatus("4");
                        orderInfo.setPaytime(new Date());
                        coalService.updateById(orderInfo);
                        ///扣点值
                        List<OrderPoundage> orderPoundage = orderPoundageService.list();
                        //工人应收金额 下单价*(1-n%) n为扣率
                        BigDecimal workerReceiveMoney = DecimalUtil.workderRealMoneyRegular(orderInfo.getOrderprice(), orderPoundage.get(0).getPoundage());
                        //工人新账户余额
                        BigDecimal workderNewAccountMoney = DecimalUtil.add(workerUserInfo.getAccountmoney(), workerReceiveMoney);
                        //记录明细
                        MoneyDetail moneyDetail = new MoneyDetail();
                        moneyDetail.setId(IdWorker.getId());
                        moneyDetail.setUserid(orderInfo.getCuserid() + "");
                        moneyDetail.setOrderid(orderInfo.getId() + "");
                        moneyDetail.setFkfserid(orderInfo.getCuserid());
                        moneyDetail.setFkfname(orderInfo.getCusername());
                        moneyDetail.setFkfphone(orderInfo.getCuserphone());
                        moneyDetail.setTrademoney(workerReceiveMoney);
                        moneyDetail.setMoneymark("商户订单支付:[商户支付金额]" + orderInfo.getPayamount() + "[平台优惠券金额]:" + orderInfo.getDiscountprice() + "微信交易凭证" + WxPayKit.xmlToMap(orderQuery));
                        moneyDetail.setSkfuserid(orderInfo.getWorkerid());
                        moneyDetail.setSkfusername(orderInfo.getWorkername());
                        moneyDetail.setSkfuserphone(orderInfo.getWorkerphone());
                        moneyDetail.setBefmoeny(workerUserInfo.getAccountmoney());
                        moneyDetail.setAftmoney(workderNewAccountMoney);
                        moneyDetail.setMoneytype("1");
                        moneyDetail.setCtime(new Date());
                        moneyDetailService.save(moneyDetail);
                        ////更新 工人新账户余额
                        workerUserInfo.setAccountmoney(workderNewAccountMoney);
                        userService.updateById(workerUserInfo);
                        ////去作废已用的优惠券
                        if (!StringUtils.isEmpty(orderInfo.getDiscountid())) {
                            Coupons coupons = new Coupons();
                            coupons.setId(Long.valueOf(orderInfo.getDiscountid()));
                            coupons.setDelflag(2);
                            couponsService.updateById(coupons);
                        }
                        NettyHandler.handleOrderWorkerId(orderInfo.getWorkerid(), orderInfo.getCusername() + "商家已付款");
                        //FIXME  通知消息 极光
                        Jpush jpush = jpushService.getById(orderInfo.getWorkerid());
                        if (!StringUtils.isEmpty(jpush)) {
                            List<String> jgusers = new ArrayList<>();
                            jgusers.add(jpush.getRegistrationid());
                            JpushTemplate.pushMessage(jgusers, orderInfo.getCusername() + "商家已付款");
                        }
                    }
                    if ("5".equals(orderInfo.getOrderstatus()) && "2".equals(orderInfo.getQxstatus())) {
                        orderInfo.setQxstatus("3");
                        coalService.updateById(orderInfo);
                    }
                }


            } else {
                log.error("资金安全日志: 交易失败" + WxPayKit.xmlToMap(orderQuery));
            }


        }
    }
}
